package com.hs.bai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hs.bai.mapper.AddrinfoMapper;
import com.hs.bai.mapper.OrderMapper;
import com.hs.bai.pojo.Order;
import com.hs.bai.service.IAddrinfoService;
import com.hs.bai.pojo.Addrinfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.dto.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 地址信息 服务实现类
 * </p>
 *
 * @author Dingkun Bai
 * @since 2022-06-13
 */
@Service
public class AddrinfoServiceImpl extends ServiceImpl<AddrinfoMapper, Addrinfo> implements IAddrinfoService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddrinfoMapper addrinfoMapper;


    /**
     *
     * 添加地址信息
     * @param addrinfo
     */
    @Transactional
    @Override
    public ResultBean saveAddInfo(Addrinfo addrinfo) {

        //添加订单出发离开的城市
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("t_a_id",addrinfo.getId());
        Order order = orderMapper.selectOne(qw);
        if (order != null) {
            String shippingAddress = addrinfo.getShippingAddress();
            int i1 = shippingAddress.indexOf("-");
            int i3 = shippingAddress.lastIndexOf("-");
            order.setDepartureCity(shippingAddress.substring(i1+1,i3));
            String receivingAddress = addrinfo.getReceivingAddress();
            int i2 = receivingAddress.indexOf("-");
            int i4 = receivingAddress.lastIndexOf("-");
            order.setDestinationCity(receivingAddress.substring(i2+1,i4));
            orderMapper.updateById(order);
            int i = addrinfoMapper.insert(addrinfo);
            return i > 0 ? ResultBean.OK("添加成功！"):ResultBean.ERROR("添加失败！");
        }
        return ResultBean.ERROR("添加失败！");
    }

    @Transactional
    @Override
    public ResultBean updateAdd(Addrinfo addrinfo) {

        //修改订单出发离开的城市
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("t_a_id",addrinfo.getId());
        Order order = orderMapper.selectOne(qw);
        if (order != null) {
            String shippingAddress = addrinfo.getShippingAddress();
            int i1 = shippingAddress.indexOf("-");
            int i3 = shippingAddress.lastIndexOf("-");
            order.setDepartureCity(shippingAddress.substring(i1+1,i3));
            String receivingAddress = addrinfo.getReceivingAddress();
            int i2 = receivingAddress.indexOf("-");
            int i4 = receivingAddress.lastIndexOf("-");
            order.setDestinationCity(receivingAddress.substring(i2+1,i4));
            orderMapper.updateById(order);
            int i = addrinfoMapper.updateById(addrinfo);
            return i > 0 ? ResultBean.OK("修改成功！"):ResultBean.ERROR("修改失败！");
        }
        return ResultBean.ERROR("修改失败！");

    }
}
